import axios, {
  AxiosError,
  AxiosRequestConfig,
  AxiosRequestHeaders,
} from "axios";
import { store } from "@/store";
import { getAuth, getCpl } from "./token";

const instance = axios.create();
instance.defaults.timeout = 60000;
instance.defaults.headers.common.Accept = "application/json";

// 请求拦截器
instance.interceptors.request.use((config) => {
  // 此处可以做公共参数的处理，例如用户auth
  (config.headers as AxiosRequestHeaders).auth = store.state.auth || getAuth();
  (config.headers as AxiosRequestHeaders).cpl = getCpl();
  config.url = `/api${config.url}`;
  return config;
});

const request = <T>(url: string, config?: AxiosRequestConfig) => {
  return instance
    .request<ResponseResolve | Blob>({ url, ...config })
    .then((response) => {
      const data = response.data;
      // 响应 Blod，下载
      if (data instanceof Blob) return data as unknown as T;
      // 响应 JSON
      return data.errorCode === 1
        ? (data.result as T)
        : Promise.reject({ response });
    })
    .catch((error: AxiosError<ResponseResolve>) => {
      console.error(error);
      const response = error.response;
      // 请求未发出
      if (!response) return Promise.reject(new Error(error.message));
      const data = response.data;
      // 请求已发出，但服务器响应的状态码不在 2xx 范围内
      return Promise.reject(
        new Error(data ? data.errorMsg : response.statusText)
      );
    });
};
export const requestGet = <T>(
  url: string,
  params?: unknown,
  config?: AxiosRequestConfig
) => {
  return request<T>(url, { ...config, params });
};
export const requestPost = <T>(
  url: string,
  data?: unknown,
  config?: AxiosRequestConfig
) => {
  return request<T>(url, { ...config, data, method: "post" });
};

interface ResponseResolve {
  errorCode: number | 1 | 501;
  errorMsg: string;
  result: unknown;
}
